/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import {Form, Icon, Input, Card, Tooltip, Button, Table, Popconfirm, Checkbox, message, Layout} from 'antd';
import {connect} from 'dva';
import {Link, routerRedux} from 'dva/router';
import request from '@/utils/request';
import groupBy from 'lodash/groupBy'
import forEach from 'lodash/forEach'
import find from 'lodash/find'
const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const {Content} = Layout;
@connect(state => ({
  roles: state.staffs,
}))
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.uuid = 0;
    this.isNew = !this.props.editRecord ? true : false;
    this.state = {
      userManageCheckedList: [],
      villageCheckedList: [],
      otherCheckedList: [],
      other: [],
      userManage: [],
      village: [],
      userIndeterminate: false,
      otherIndeterminate: false,
      villageIndeterminate: false,
      checkAll: false,
      otherCheckAll: false,
      villageCheckAll: false,
      editRecord: {},
      你好评: '234',
      group: {}
    }
  }

  componentDidMount() {
    if (this.props.findChildFunc) {
      this.props.findChildFunc(this.getGroup);
    }
    const {dispatch} = this.props;

    const that = this;

    request(`/permissions`, {
      method: 'GET',
      params: {
        return:'all'
      }
    }).then((response)=> {
      console.log('response', response)
      const group = groupBy(response.data.data, 'group')
      console.log('group', group);
      forEach(group, function (value, key) {
        that.setState({
          [key]: value.reduce((result, item)=> {
            item.label = item.display_name;
            item.value = item.name;
            result.push({label: item.display_name, value: item.name})
            return result
          }, [])
        })
        that.setState({
          [key + 'CheckedList']: [],
          [key + 'Indeterminate']: false,
          [key + 'CheckAll']: false,
        })

      });

      that.setState({
        group: group
      }, function () {
        if (this.isNew) {
          console.log('新建角色')
        } else {
          console.log('修改角色')
          const id = this.props.editRecord.id;
          dispatch({
            type: 'Roles/fetchOneusergroup',
            payload: {
              id
            },
            callback: function () {
              const {roles}=that.props;
              console.log('staffs.js',roles)
              const editRecord=roles.editRecord
              console.log('editRecord',editRecord)

              const selectGroup = groupBy(editRecord.permissions.data, 'group')
              console.log('selectGroup', selectGroup)
              forEach(selectGroup, function (value, key) {
                that.setState({
                  [key + 'CheckedList']: value.reduce((result, item)=> {
                    result.push(item.name)
                    return result
                  }, [])
                }, function () {
                  that.setState({
                    [key + 'Indeterminate']: !!this.state[key + 'CheckedList'].length && (this.state[key + 'CheckedList'].length < this.state[key].length),
                    [key + 'CheckAll']: this.state[key + 'CheckedList'].length === this.state[key].length,
                  })
                })
              });

            }
          });

        }
      })
    })
  }
  getGroup=()=>{
    const that=this
    const permissionsNames = [];
    const permissions = [];
    console.log('that.state.group',that.state.group)
    forEach(that.state.group, function (value, key) {
      permissionsNames.push(...that.state[key + 'CheckedList'])
    });
    console.log('permissionsNames',permissionsNames)
    console.log('that.state.group',that.state.group)
    for(let i=0;i<permissionsNames.length;i++){
      forEach(that.state.group, function (value, key) {
        const canFind=find(value,{name:permissionsNames[i]})
        console.log('canFind',canFind)
        if(canFind){
          permissions.push(canFind.value)
        }
      });
    }
    return permissions
  }
  handleSubmit = (e)=> {
    e.preventDefault();
    const that = this;
    const id = this.props.match.params.id;
    this.props.form.validateFields({force: true},
      (err, values) => {
        if (!err) {
          console.log(values)
          const type = this.isNew ? 'Roles/add' : 'Roles/edit';
          const msg = this.isNew ? '添加角色成功' : '修改角色成功';
          const data = this.isNew ? {
            permissions: this.state.otherCheckedList.concat(this.state.userManageCheckedList),
            ...values
          } : {
            id,
            permissions: this.state.otherCheckedList.concat(this.state.userManageCheckedList),
            ...values
          };
          this.props.dispatch({
            type: type,
            payload: {
              data
            },
            callback: function () {
              message.success(msg)
              that.props.dispatch(routerRedux.replace(`/main/system_manage/account_manage/user_group_manage`));
            }
          });
        }
      }
    );
  }
  handleSubmit2 = (e)=> {
    e.preventDefault();
    const that = this;
    const id = this.props.match.params.id;
    this.props.form.validateFields({force: true},
      (err, values) => {
        if (!err) {
          console.log(values)
          const type = this.isNew ? 'Roles/add' : 'Roles/edit';
          const msg = this.isNew ? '添加角色成功' : '修改角色成功';
          const permissions = [];
          forEach(that.state.group, function (value, key) {
            permissions.push(...that.state[key + 'CheckedList'])
          });
          // console.log('permissions',permissions)
          const company_code = sessionStorage.getItem('company_code');
          const data = this.isNew ? {
            permissions: permissions,
            ...values
          } : {
            id,
            permissions: permissions,
            ...values
          };
          this.props.dispatch({
            type: type,
            payload: {
              data
            },
            callback: function () {
              message.success(msg)
              that.props.dispatch(routerRedux.replace(`/${company_code}/main/system_manage/account_manage/user_group_manage`));
            }
          });
        }
      }
    );
  }
  onChange = (userManageCheckedList) => {
    this.setState({
      userManageCheckedList,
      userIndeterminate: !!userManageCheckedList.length && (userManageCheckedList.length < this.state.userManage.length),
      checkAll: userManageCheckedList.length === this.state.userManage.length,
    });
  }
  onChange2 = (nodes, key) => {
    console.log(nodes)
    console.log(key)
    this.setState({
      [key + 'CheckedList']: nodes,
      [key + 'Indeterminate']: !!nodes.length && (nodes.length < this.state[key].length),
      [key + 'CheckAll']: nodes.length === this.state[key].length,
    })
    // this.setState({
    //   userManageCheckedList,
    //   userIndeterminate: !!userManageCheckedList.length && (userManageCheckedList.length < this.state.userManage.length),
    //   checkAll: userManageCheckedList.length === this.state.userManage.length,
    // });
  }
  onCheckAllChange2 = (e, key) => {
    this.setState({
      [key + 'CheckedList']: e.target.checked ? this.state[key].map((item, index)=> {
        return item.value
      }) : [],
      [key + 'Indeterminate']: false,
      [key + 'CheckAll']: e.target.checked,
    });
  }
  onCheckAllChange = (e) => {
    this.setState({
      userManageCheckedList: e.target.checked ? this.state.userManage.map((item, index)=> {
        return item.value
      }) : [],
      userIndeterminate: false,
      checkAll: e.target.checked,
    });
  }
  onChangeOther = (otherCheckedList) => {
    this.setState({
      otherCheckedList,
      otherIndeterminate: !!otherCheckedList.length && (otherCheckedList.length < this.state.other.length),
      otherCheckAll: otherCheckedList.length === this.state.other.length,
    });
  }
  onCheckAllChangeOther = (e) => {
    this.setState({
      otherCheckedList: e.target.checked ? this.state.other.map((item, index)=> {
        return item.value
      }) : [],
      otherIndeterminate: false,
      otherCheckAll: e.target.checked,
    });
  }
  renderXheckGroup = (group)=> {
    const that = this
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: {span: 24},
        sm: {offset: 5, span: 15},
      }
    }
    let result = []
    forEach(group, function (value, key) {
      result.push((
        <FormItem
          style={{marginBottom:'12px'}}
          key={key}
          {...formItemLayoutWithOutLabel}
        >
          <div className="checkgroup-title">
            <Checkbox
              style={{fontWeight:'700',color:'#00a056'}}
              indeterminate={that.state[key + 'Indeterminate']}
              onChange={(e)=>that.onCheckAllChange2(e, key)}
              checked={that.state[key + 'CheckAll']}
            >
              {key}
            </Checkbox>
          </div>
          <CheckboxGroup options={that.state[key]} value={that.state[key + 'CheckedList']}
                         onChange={(node)=>that.onChange2(node, key)}/>
        </FormItem>
      ))
    });

    return result
  }

  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15},
      }
    };
    const {getFieldDecorator} = this.props.form;
    const {roles:{editRecord}}=this.props
    return (
      <div >
        <Form>
          <FormItem
            style={{marginTop:'10px'}}
            {...formItemLayoutWithLabel}
            label='角色名称'
          >
            {getFieldDecorator('display_name', {
              initialValue: this.props.editRecord ? this.props.editRecord.display_name : '',
              rules: [{
                required: true,
              }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label='描述'
          >
            {getFieldDecorator('description', {
              initialValue: this.props.editRecord ? this.props.editRecord.description : '',
            })(
              <Input />
            )}
          </FormItem>
          <h3 style={{textAlign:'center',margin:0}}>权限信息</h3>
          {this.renderXheckGroup(this.state.group)}
        </Form>
      </div >
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default AddPoliciesFormWrap;
